package com.yt.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.util.StreamUtils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * @Description ：
 * @Author ： 解风
 * @Date ： 2017/09/19 09:59
 */
@Slf4j
public class FileUtils {

    /**
     * 生成本地文件
     *
     * @param str     文件内容
     * @param file    文件路径
     * @param charset 编码格式
     * @return
     */
    public static boolean stringWriteToFile(String str, String file, String charset) {
        try {
            File destFile = new File(file);
            if (!destFile.getParentFile().exists()) {
                System.out.println("目标文件所在目录不存在，准备创建它！");
                if (!destFile.getParentFile().mkdirs()) {
                    System.out.println("创建目标文件所在目录失败！");
                    return false;
                }
            }
            if (!destFile.exists()) {
                destFile.createNewFile();
                destFile.setReadable(true, false);
                destFile.setWritable(true, false);
                //destFile.setExecutable(true,false);
            }
            FileOutputStream out = new FileOutputStream(file);
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out, charset));
            int len = 4096;
            int c = str.length() / len;
            int lef = str.length() % len;
            int index = 0;
            for (int i = 0; i < c; ) {
                bw.write(str, index, len);
                ++i;
                index = i * len;
            }
            bw.write(str, index, lef);
            bw.flush();
            bw.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("写文件错误：" + e.getMessage());
        }
        return false;
    }

    /**
     * 上传文件
     *
     * @param file
     * @param filePath
     * @param fileName
     * @throws Exception
     */
    public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
        File targetFile = new File(filePath);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        FileOutputStream out = new FileOutputStream(filePath + fileName);
        out.write(file);
        out.flush();
        out.close();
    }

    public static void main(String[] args) {
        String file = "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAA0JCgsKCA0LCgsODg0PEyAVExISEyccHhcgLikxMC4pLSwzOko+MzZGNywtQFdBRkxOUlNSMj5aYVpQYEpRUk//2wBDAQ4ODhMREyYVFSZPNS01T09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT0//wAARCAD4APgDASIAAhEBAxEB/8QAGwAAAQUBAQAAAAAAAAAAAAAABAACAwUGAQf/xAA+EAABAwMDAgQEBQQBAQcFAAABAgMRAAQhBRIxQVEGEyJhMnGBkRRCobHBI9Hh8FIVBxZigpKi8SQzU3Ky/8QAGgEAAgMBAQAAAAAAAAAAAAAAAgMAAQQFBv/EACkRAAICAgMAAQMEAgMAAAAAAAABAhEDIQQSMUETIlEUIzJhBXGBkfH/2gAMAwEAAhEDEQA/ANtuTyEHP+96YtU52GP996Db1ayWIF0ziikPtuIlL7ZntQlg2oX6LK0KylW78onn9aweoXbt0+p11zKvyngVoPF61ayWIF0ziikPtuIlL7ZntQlf8zfUlG5ubFulLiVJKVJIII9jWL8YOj/ALxW6UmdrckdpP8Aiof+zfUlG5ubFSSQpIWDPwxg/uKG8UOed4peKFYRtT9hmh8ZejVaY6VMJz0/3pVgN0SCf9+lUGkOK8oer/fvV23kcg/786plEkr9/v8A4rjnmKSRJg45roBj4R+v96RJAwj9VVRZmdZaaatvIKBMzO3+aK0bTmmbJLqm0gr6mi9Ss2boDzE7VDMyRTr1i48ppNuwwtIAHqVBH6GkP8GpfDI7gshBBUlIrO6vpSX2tps+rmIia0lzYn8Ok+YEL4nmDQy7NFqzLrq3XVDKlH+BihWth+6QJ4GS63pzqS36Q8RJmrDUnkJvGyqDKgKg8P8AmIddQEp8pSioc80Jq2+41pi3bJ+MKMdAKNvs0L69bLfUGFFl1KIC1IO2sAvV3bILau0qcu0naYwIr0K5dh1DQO5YGR7d6rjY6S087f3Ful53op1Mp+gOKb2S9Fwg5GAf1B24Qlxw7dxwkdBQryoIxV74ycXc3Fvc/kUiEgcCsuVGauLtWSap0Ru5JqRlza2UHrTDTFGBRAF34ffIXdIBO3ZNDLcQFLKjTvD76WFvlaAtLidpnkfKhrps+Yo9Jpfyx0oSUE34MU7uV7VMlSUwpRgUOlAQnzF8DgUK66Vq5xRCg9epL+Bs7R7V1u5UTkk1WJknFEIBHyq0Vdlq2+Y5zSoNMEAkTSqyB6nVDIgU38UsHC1fKuLQocE03ZImJqUUE/8AUHHEhNworSOATxXCyi4EtHPagloIGM0xu4Uy4DMVCzYaToaRbhx9oBfINOfat21lHpyeKk0PWG7m38h1yFRAMV1ds49ewp1KmgcQmD+9Z5XezXBKtEWj3FvpurLuA0SpSCmE4jihroOPXzr4ChvWVc1YIsVMamCVS2rhMUd+EbUqfL+6T/aij+RGWCU7I9N8wADcr7f4q9YKgPUT9f8A4oJlppoAwkfQf2ohELI2nHz/AM0diqDAtI52/pXfNnCQj/0pqFBCfiP2J/vTLi48lrfucj2mqbouMXJ0jlyl5Sdydu4DHA/mmJviloFRAxmelZ6+8TutOLQ36tvWeKor3Xr1aCqAkO9AM0Di5O0alWNdZOzS3evWorkBNj7lSbqFJ2pUZ7V5+5q124oqLhE9qHdv7lwyXVfep/Tt7HfqYJ6R6DqPiNltpSWlFTh4jtWVvL1d04XFqJJ5NZ9V08TlZqRL61DJUaZY4RVMXk5eXKUqCQqT7V0vKUkgnBoZlCQZIzUqjKcVrSMbds6lZTgGnJXtO4GKjScU8HtUo1I666XVEnrXJgU0UqkDgIzTJxXCaVKgOwKVKlQH/9k=";
        try {
            try {
                // Base64解码
                byte[] bytes = Base64.decodeBase64(file);
                for (int i = 0; i < bytes.length; ++i) {
                    if (bytes[i] < 0) {// 调整异常数据
                        bytes[i] += 256;
                    }
                }
                // 生成jpeg图片
                OutputStream out = new FileOutputStream("D://112.png");
                out.write(bytes);
                out.flush();
                out.close();
            } catch (Exception e) {
            }
            uploadFile(Base64.decodeBase64(file), "D:/", "111.png");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 读文件
     *
     * @param path
     * @return
     */
    public static String readFile(String path) {
        if (path == null || "".equals(path.trim())) return null;

        File file = new File(path);
        BufferedReader reader = null;
        StringBuilder str = new StringBuilder();
        try {
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8));
            String temp = null;
            while ((temp = reader.readLine()) != null) {
                str.append(temp);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
//            log.error("文件读取失败，路径为：{}", path);
            throw new RuntimeException("文件读取失败", e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
        return str.toString();
    }

    public static boolean saveFile(String queryData, String filePath) {

        try {
            File destFile = new File(filePath);
            //判断目标文件所在的目录是否存在
            if (!destFile.getParentFile().exists()) {
                //如果目标文件所在的目录不存在，则创建父目录
                System.out.println("目标文件所在目录不存在，准备创建它！");
                if (!destFile.getParentFile().mkdirs()) {
                    System.out.println("创建目标文件所在目录失败！");
                    return false;
                }
            }
            if (!destFile.exists()) {
                destFile.createNewFile();
                destFile.setReadable(true, false);
                destFile.setWritable(true, false);
                //destFile.setExecutable(true,false);
            }
            FileOutputStream out = new FileOutputStream(filePath);
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8));
            int len = 4096;
            int c = queryData.length() / len;
            int lef = queryData.length() % len;
            int index = 0;
            for (int i = 0; i < c; ) {
                bw.write(queryData, index, len);
                ++i;
                index = i * len;
            }
            bw.write(queryData, index, lef);
            bw.flush();
            bw.close();
            return true;
        } catch (Exception e) {
            System.out.println("写文件错误：" + e.getMessage());
        }
        return false;

    }

    //url文件下载
    public static void downLoad(String filePath, String targerPath) throws Throwable {
        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
            HttpGet httpget = new HttpGet(filePath);
            httpget.setConfig(RequestConfig.custom()
                    .setConnectionRequestTimeout(3 * 1000)
                    .setConnectTimeout(3 * 1000)
                    .setSocketTimeout(3 * 1000)
                    .build());
            try (CloseableHttpResponse response = httpclient.execute(httpget)) {
                org.apache.http.HttpEntity entity = response.getEntity();
                File desc = new File(targerPath);
                File folder = desc.getParentFile();
                folder.mkdirs();
                try (InputStream is = entity.getContent();
                     OutputStream os = new FileOutputStream(desc)) {
                    StreamUtils.copy(is, os);
                }
            } catch (Throwable e) {
                throw new Throwable(filePath + "文件下载失败......", e);
            }
        }
    }

    //url文件下载
    public static byte[] downLoad(String filePath) {
        try {
            //new一个URL对象
            URL url = new URL(filePath);
            //打开链接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //设置请求方式为"GET"
            conn.setRequestMethod("GET");
            //超时响应时间为5秒
            conn.setConnectTimeout(5 * 1000);
            //通过输入流获取图片数据
            InputStream inStream = conn.getInputStream();
            return inputStream2byte(inStream);
        } catch (Exception e) {
            log.error("downLoad is error", e);
        }
        return null;
    }

    public static boolean isImage(File file) {
        try {
            Image image = ImageIO.read(file);
            return image != null;
        } catch (IOException ex) {
            return false;
        }
    }

    public static boolean isImage(InputStream input) {
        try {
            Image image = ImageIO.read(input);
            return image != null;
        } catch (IOException ex) {
            return false;
        }
    }

    public static String getFileName(String filename) {
        log.info("filename:{}", filename);
        String fileName = filename.substring(0, filename.lastIndexOf("."));
        return fileName;
    }

    public static String getFileExtName(String filename) {
        String fileExtName = filename.substring(filename.lastIndexOf(".") + 1);
        return fileExtName;
    }

    public static final InputStream byte2InputStream(byte[] buf) {
        return new ByteArrayInputStream(buf);
    }

    public static final byte[] inputStream2byte(InputStream inStream) throws IOException {
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
        byte[] buff = new byte[100];
        int rc = 0;
        while ((rc = inStream.read(buff, 0, 100)) > 0) {
            swapStream.write(buff, 0, rc);
        }
        //关闭输入流
        inStream.close();
        byte[] in2b = swapStream.toByteArray();
        return in2b;
    }

    public static final byte[] image2byte(BufferedImage bufferedImage, String fileExtName) throws IOException {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage, fileExtName, os);
        return os.toByteArray();
    }

    //检查兼容
    public static String checkCompatible(String originalFilename) {
        log.info("----originalFilename:" + originalFilename);
        int unixSep = originalFilename.lastIndexOf('/');
        // Check for Windows-style path
        int winSep = originalFilename.lastIndexOf('\\');
        // Cut off at latest possible point
        int pos = (winSep > unixSep ? winSep : unixSep);
        if (pos != -1) {
            // Any sort of path separator found...
            originalFilename = originalFilename.substring(pos + 1);
        }
        return originalFilename;
    }
}
